import { NextRequest, NextResponse } from "next/server"; import { basename } from "node:path"; import { readUploadBuffer, resolveUploadPath } from "@/lib/chat-store"; function guessContentType(fileName: string) { const lower = fileName.toLowerCase(); if (lower.endsWith(".png")) return "image/png"; if (lower.endsWith(".jpg") || lower.endsWith(".jpeg")) return "image/jpeg"; if (lower.endsWith(".gif")) return "image/gif"; if (lower.endsWith(".webp")) return "image/webp"; if (lower.endsWith(".svg")) return "image/svg+xml"; if (lower.endsWith(".pdf")) return "application/pdf"; if (lower.endsWith(".txt")) return "text/plain; charset=utf-8"; if (lower.endsWith(".zip")) return "application/zip"; if (lower.endsWith(".rar")) return "application/vnd.rar"; if (lower.endsWith(".doc")) return "application/msword"; if (lower.endsWith(".docx")) { return "application/vnd.openxmlformats-officedocument.wordprocessingml.document"; } if (lower.endsWith(".xls")) return "application/vnd.ms-excel"; if (lower.endsWith(".xlsx")) { return "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; } return "application/octet-stream"; } export async function GET( request: NextRequest, context: { params: Promise<{ storageKey: string }> } ) { const { storageKey } = await context.params; const safeStorageKey = basename(storageKey); try { const fileBuffer = await readUploadBuffer(safeStorageKey); const contentType = guessContentType(safeStorageKey); const download = request.nextUrl.searchParams.get("download") === "1"; return new NextResponse(fileBuffer, { headers: { "Content-Type": contentType, "Content-Disposition": `${download ? "attachment" : "inline"}; filename="${encodeURIComponent(safeStorageKey)}"`, "Cache-Control": "private, max-age=31536000, immutable" } }); } catch { return NextResponse.json({ error: "文件不存在" }, { status: 404 }); } }